package com.share.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.share.common.core.exception.ServiceException;
import com.share.user.api.domain.UpdateUserLogin;
import com.share.user.domain.UserInfo;
import com.share.user.domain.UserLoginLog;
import com.share.user.mapper.UserInfoMapper;
import com.share.user.mapper.UserLoginLogMapper;
import com.share.user.service.IUserInfoService;
import jakarta.annotation.Resource;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import java.util.Collection;

/**
 * Created by IntelliJ IDEA.
 *
 * &#064;Author  : zhang
 * &#064;create  2025/3/27 16:25
 */
@Service
public class UserInfoService  extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService{

    @Resource
    private WxMaService wxMaService;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private UserLoginLogMapper userLoginLogMapper;

    @Override
    public UserInfo wxLogin(String code) {
        String openId = null;
        try {
            val sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openId = sessionInfo.getOpenid();

        } catch (WxErrorException e) {
            throw new ServiceException("微信登录失败");
        }
        UserInfo userInfo = this.getOne(new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getWxOpenId, openId));
        if(userInfo == null){
            userInfo = new UserInfo();
            userInfo.setNickName(String.valueOf(System.currentTimeMillis()));
            userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            userInfo.setWxOpenId(openId);
            this.save(userInfo);
        }
        return userInfo;


    }

    @Override
    public Boolean updateUserLogin(UpdateUserLogin updateUserLogin) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(updateUserLogin.getUserId());
        userInfo.setLastLoginIp(updateUserLogin.getLastLoginIp());
        userInfo.setLastLoginTime(updateUserLogin.getLastLoginTime());
        userInfoMapper.updateById(userInfo);

        //登录日志
        UserLoginLog userLoginLog = new UserLoginLog();
        userLoginLog.setUserId(userInfo.getId());
        userLoginLog.setMsg("小程序登录");
        userLoginLog.setIpaddr(updateUserLogin.getLastLoginIp());
        userLoginLogMapper.insert(userLoginLog);
        return true;
    }
}
